import ubinascii
import gc


def string_to_hex(input_str):
    """字符串 to hex"""
    return input_str.encode("utf-8").hex()


def print_gc_info():
    """输入当前gc信息"""
    free_m = gc.mem_free()
    alloc_m = gc.mem_alloc()
    print("free: ", free_m / 1024, "KB alloc_m: ", alloc_m / 1024, "KB")


def collect_gc(print_stdout=False):
    """回收gc"""
    gc.collect()
    if print_stdout:
        print_gc_info()


def url_escape(s):
    """url编码"""
    return "".join(c if c.isalpha() or c.isdigit() else "%%%02x" % ord(c) for c in s)


def decode_base64(base64_str):
    "decode base64 str to ascii"
    return ubinascii.a2b_base64(base64_str)


def is_ascii(ch):
    """check ascii char"""
    return len(ch.encode("utf-8")) == 1


def get_data_value(data, key_path, index=None):
    """
    read data value by key path, support List or Dict
    path format "a.b.c"
    """
    # print(data, key_path, index, isinstance(data, list), isinstance(data, dict))
    if isinstance(data, list):
        if index is not None:
            if index <= len(data) - 1:
                return data[index]
            else:
                return ""
        else:
            return data

    if isinstance(data, dict):
        paths = key_path.split(".")
        # print(paths)
        if len(paths) == 0:
            return data

        if paths[0] == "":
            return data

        if paths[0] in data:
            return get_data_value(data[paths[0]], "".join(paths[1:]), index)
        else:
            return ""

    return data

def integerToRGB(colorInt):
    r = (colorInt >> 16) & 0xFF
    g = (colorInt >> 8) & 0xFF
    b = colorInt & 0xFF
    return (r, g, b)


if __name__ == "__main__":
    print(string_to_hex("hanxiaoxin"))
    print_gc_info()
    collect_gc()
    print_gc_info()
